package cn.yeamin.spring.boot.exception;

import cn.yeamin.spring.boot.vo.ErrorInfo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @packageName: 包名: cn.yeamin.spring.boot.exception
 * @classDesc: 类功能描述:(全局捕获异常处理)
 * @author: Administrator
 * @createTime: 2017/7/18 19:28
 * @version: v1.0
 * @copyright:奕明(上海)影视传媒有限公司
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    public static final String DEFAULT_ERROR_VIEW = "error";

    /**
     * @methodDesc: 方法描述:(全局出现异常后跳转到error.html页面)
     * @author: 李彤
     * @version: v1.0
     * @copyright:奕明(上海)影视传媒有限公司
     */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.addObject("exception", e);
        mv.addObject("url", req.getRequestURL());
        mv.setViewName(DEFAULT_ERROR_VIEW);
        return mv;
    }

    /**
     * @methodDesc: 方法描述:(全局出现异常后给客户端以JSON形式提示)
     * @author: 李彤
     * @version: v1.0
     * @copyright:奕明(上海)影视传媒有限公司
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, RuntimeException e) throws Exception {
        ErrorInfo<String> r = new ErrorInfo<>();
        r.setMessage(e.getMessage());
        r.setCode(ErrorInfo.ERROR);
        r.setData("服务器异常,请稍后再试!");
        r.setUrl(req.getRequestURL().toString());
        return r;
    }
}
